import type { PlasmoCSConfig } from "plasmo"

import { sendToBackground } from "@plasmohq/messaging"

// 获取cookie > auth_token
// const getAuthToken = () => document.cookie.match(/auth_token=([^;]+)/)?.at(1)

const getContactInfo = (): ContactInfo => {
  const initData = {
    phone_list: [],
    email_list: [],
    company_type: "",
    set_up_time: "",
    registered_capital: "",
    operating_condition: ""
  }
  const htmlStr = document.body.innerHTML
  const regex = /<script id="__NEXT_DATA__" type="application\/json">(.*?)<\/script>/s
  const match = htmlStr.match(regex)
  if (!match) return initData
  try {
    const data = JSON.parse(match[1])
    const target = data.props.pageProps.dehydratedState.queries.find((item) => item.state.data.data.companyList)
    const companyList = target.state.data.data.companyList
    const { phoneList, emailList, estiblishTime, regStatus, regCapital, orgType } = companyList[0]
    return {
      phone_list: phoneList?.map((number) => ({ number, comment: "固定电话或移动电话" })) || [],
      email_list: emailList || [],
      company_type: orgType || "",
      set_up_time: estiblishTime?.split(" ")?.at(0) || "",
      registered_capital: regCapital || "",
      operating_condition: regStatus || ""
    }
  } catch (error) {
    return initData
  }
}

document.addEventListener("DOMContentLoaded", async () => {
  // 判断url是否存在auth_token参数
  const url = new URL(window.location.href)
  const authToken = url.searchParams.get("auth_token")
  // 非插件打开页面，不进行任何处理
  if (!authToken) return
  sendToBackground({ name: "contactInfo", body: { isTYC: true, data: getContactInfo() } })
})

export const config: PlasmoCSConfig = {
  matches: ["https://www.tianyancha.com/nsearch*"],
  run_at: "document_start",
  all_frames: true
}
